<?php

namespace Cck\ArticlesSystem\Http\Controllers;

use Illuminate\Http\Request;
use Cck\ArticlesSystem\Http\Models\Keyword;
use Cck\ArticlesSystem\Http\Resources\KeywordResource;

class KeywordsController extends Controller
{
    public function index(Request $request)
    {
        $pageSize = (int)max($request->query('page_size', 15), 10);
        $page = (int)max($request->query('page', 1), 1);

        $tags = $request->get('tags', []);

        $keywords = Keyword::query()
            ->when($request->get('user_id'), function ($q, $userId) {
                $q->where('user_id', (int)$userId);
            })
            ->when(is_array($tags) && $tags, function ($q) use ($tags) {
                $q->whereIn('tag_id', $tags);
            })
            ->when($request->get('used', '') !== '', function ($q) use ($request) {
                (boolean)$request->get('used') ? $q->whereNotNull('used_at') : $q->whereNull('used_at');
            }, function ($q) {
                $q->whereNull('used_at');
            })
            ->with($this->getWith())
            ->paginate($pageSize, ['*'], 'page', $page);

        return KeywordResource::collection($keywords);
    }
}
